using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace WPF_MVVM_Test.Services.Plan
{
    /// <summary>
    /// 字符串到Decimal的JSON转换器 - 专门用于planQuantity字段
    /// </summary>
    public class StringToDecimalConverter : JsonConverter<decimal>
    {
        public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            switch (reader.TokenType)
            {
                case JsonTokenType.String:
                    var stringValue = reader.GetString();
                    if (string.IsNullOrWhiteSpace(stringValue))
                        return 0m;
                    
                    // 尝试解析decimal
                    if (decimal.TryParse(stringValue, NumberStyles.Any, CultureInfo.InvariantCulture, out var decimalValue))
                        return decimalValue;
                    
                    // 如果包含逗号，尝试替换为点号
                    if (stringValue.Contains(","))
                    {
                        var normalizedValue = stringValue.Replace(",", ".");
                        if (decimal.TryParse(normalizedValue, NumberStyles.Any, CultureInfo.InvariantCulture, out var decimalValue2))
                            return decimalValue2;
                    }
                    
                    System.Diagnostics.Debug.WriteLine($"⚠️ 无法解析planQuantity值: '{stringValue}'，使用默认值0");
                    return 0m;
                    
                case JsonTokenType.Number:
                    return reader.GetDecimal();
                    
                case JsonTokenType.Null:
                    return 0m;
                    
                default:
                    System.Diagnostics.Debug.WriteLine($"⚠️ planQuantity字段意外的JSON类型 {reader.TokenType}，使用默认值0");
                    return 0m;
            }
        }

        public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
        {
            writer.WriteNumberValue(value);
        }
    }
}